package com.mmlc.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mmlc.meimei.lichengkongjian.R;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/7/7.
 */
public class BladeView extends View {

    private OnItemClickListener mOnItemClickListener;
    ArrayList<String> section = new ArrayList<>();
    int startHeight = 0;
    /**
     * 单个字体高度
     */
    int singleHeight;
    int choose = -1;
    Paint paint = new Paint();
    boolean showBkg = false;
    private PopupWindow mPopupWindow;
    private TextView mPopupText;
    private Handler handler = new Handler();
    DisplayMetrics metrics;

    public BladeView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        metrics = getResources().getDisplayMetrics();
        getSingleHeight();
    }

    private void getSingleHeight() {
        singleHeight = getResources().getDisplayMetrics().heightPixels * 3 / 4 / 27;
        paint.setColor(Color.BLACK);
        paint.setTypeface(Typeface.DEFAULT_BOLD);
        paint.setFakeBoldText(true);
        paint.setAntiAlias(true);
        paint.setTextSize(12 * metrics.density);

        Rect textBound = new Rect();
        paint.getTextBounds("A", 0, 1, textBound);
        int textHeight = textBound.height();
        if (textHeight > singleHeight) {
            singleHeight = textHeight;
        }
    }

    public BladeView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BladeView(Context context) {
        this(context, null, 0);
    }

    public void setSection(ArrayList<String> section) {
        this.section.addAll(section);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (showBkg) {
            canvas.drawColor(Color.parseColor("#00000000"));
        }

        int width = getMeasuredWidth();

        if (section != null && section.size() > 0) {
            startHeight = (getMeasuredHeight() - singleHeight * section.size()) / 2;
            for (int i = 0; i < section.size(); i++) {
                paint.setColor(Color.BLACK);
                paint.setTypeface(Typeface.DEFAULT_BOLD);
                paint.setFakeBoldText(true);
                paint.setAntiAlias(true);
                paint.setTextSize(12 * metrics.density);
                if (i == choose) {
                    paint.setColor(Color.parseColor("#3399ff"));
                }
                float xPos = width / 2 - paint.measureText(section.get(i)) / 2;
                float yPos = startHeight + singleHeight * i + (float) singleHeight / 2;
                canvas.drawText(section.get(i), xPos, yPos, paint);
                paint.reset();
            }
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final int action = event.getAction();
        final float y = event.getY();
        final int oldChoose = choose;
        final int c = y - startHeight < 0 || y + startHeight > getMeasuredHeight() ? -1 : (int) ((y - startHeight) / singleHeight);

        if (c < 0) return false;

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                showBkg = true;
                if (oldChoose != c) {
                    if (c >= 0 && c < section.size()) {
                        performItemClicked(c);
                        choose = c;
                        invalidate();
                    }
                }

                break;
            case MotionEvent.ACTION_MOVE:
                if (oldChoose != c) {
                    if (c >= 0 && c < section.size()) {
                        performItemClicked(c);
                        choose = c;
                        invalidate();
                    } else {
                        dismissPopup();
                    }
                }
                break;
            case MotionEvent.ACTION_UP:
                showBkg = false;
                choose = -1;
                dismissPopup();
                invalidate();
                break;
        }
        return true;
    }

    private void showPopup(int item) {
        if (mPopupWindow == null) {
            handler.removeCallbacks(dismissRunnable);
            View view = LayoutInflater.from(getContext()).inflate(R.layout.pop_blade_text, null);// new TextView(getContext());
            mPopupText = (TextView) view.findViewById(R.id.text);
//            mPopupText.setBackgroundColor(Color.GRAY);
//            mPopupText.setTextColor(Color.CYAN);
//            mPopupText.setWidth((int) (67 * metrics.density));
//            mPopupText.setHeight((int) (67 * metrics.density));
//            mPopupText.setTextSize(48 * metrics.widthPixels/1080);
//            mPopupText.setGravity(Gravity.CENTER);
            mPopupWindow = new PopupWindow(view, RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        }

        String text = section.get(item);

        mPopupText.setText(text);
        if (mPopupWindow.isShowing()) {
            mPopupWindow.update();
        } else {
            mPopupWindow.showAtLocation(getRootView(),
                    Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
        }

        dismissPopup();
    }

    private void dismissPopup() {
        handler.removeCallbacks(dismissRunnable);
        handler.postDelayed(dismissRunnable, 800);
    }

    Runnable dismissRunnable = new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (mPopupWindow != null) {
                mPopupWindow.dismiss();
                invalidate();
            }
        }
    };

    public boolean onTouchEvent(MotionEvent event) {
        return super.onTouchEvent(event);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }

    private void performItemClicked(int item) {
        if (mOnItemClickListener != null) {
            mOnItemClickListener.onItemClick(section.get(item));
            showPopup(item);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(String s);
    }
}
